<template class="question-list-view">
  <TeacherLayout>
    <el-card class="question-list-card">
      <template #header>
        <div class="card-header">
          <span>题库管理</span>
          <el-button type="primary" @click="handleAdd">添加题目</el-button>
        </div>
      </template>
        <div class="search-bar">
          <el-input v-model="searchQuery" placeholder="请输入题目内容" prefix-icon="Search" style="width: 400px;" />
          <el-select v-model="courseFilter" placeholder="选择课程" style="width: 200px; margin-left: 10px;">
            <el-option label="全部课程" value=""></el-option>
            <el-option label="高等数学" value="1"></el-option>
            <el-option label="线性代数" value="2"></el-option>
            <el-option label="概率论" value="3"></el-option>
          </el-select>
          <el-select v-model="typeFilter" placeholder="选择题型" style="width: 200px; margin-left: 10px;">
            <el-option label="全部题型" value=""></el-option>
            <el-option label="单选题" value="1"></el-option>
            <el-option label="多选题" value="2"></el-option>
            <el-option label="判断题" value="3"></el-option>
            <el-option label="简答题" value="4"></el-option>
          </el-select>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
        <el-table :data="questionsData" style="width: 100%" stripe highlight-current-row>
          <el-table-column prop="questionId" label="题目ID" width="80" align="center"></el-table-column>
          <el-table-column prop="course" label="所属课程" width="100" align="center">
            <template #default="{ row }">
              <el-tag size="small" type="info">{{ row.course }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="题型" width="100" align="center">
            <template #default="{ row }">
              <el-tag size="small" :type="getTypeTagType(row.typeId)">{{ row.type }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="题目详情" min-width="400">
            <template #default="{ row }">
              <div class="question-detail">
                <div class="question-content"><strong>题目：</strong>{{ row.questionContent }}</div>
                <!-- 显示选项（针对单选题和多选题） -->
                <template v-if="[1, 2].includes(row.typeId)">
                  <div class="options">
                    <div class="option-item" :class="{ 'correct-option': row.correctAnswer.includes('A') }">
                      <span class="option-label">A.</span> {{ row.optionA || '-' }}
                    </div>
                    <div class="option-item" :class="{ 'correct-option': row.correctAnswer.includes('B') }">
                      <span class="option-label">B.</span> {{ row.optionB || '-' }}
                    </div>
                    <div class="option-item" :class="{ 'correct-option': row.correctAnswer.includes('C') }">
                      <span class="option-label">C.</span> {{ row.optionC || '-' }}
                    </div>
                    <div class="option-item" :class="{ 'correct-option': row.correctAnswer.includes('D') }">
                      <span class="option-label">D.</span> {{ row.optionD || '-' }}
                    </div>
                  </div>
                </template>
                <!-- 显示答案 -->
                <div class="answer-info">
                  <strong>正确答案：</strong>
                  <el-tag type="success" size="small">{{ row.correctAnswer }}</el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="分值" width="80" align="center">
            <template #default="{ row }">
              <span class="score-value">{{ row.score }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="getDifficultyTagType(row.difficulty)" size="small" effect="dark">
                {{ row.difficulty }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" icon="Edit" circle @click="handleEdit(row)" title="编辑"></el-button>
              <el-button type="danger" size="small" icon="Delete" circle @click="handleDelete(row.questionId)"
                title="删除"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </TeacherLayout>
  </template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Search } from '@element-plus/icons-vue'
import { get } from '../../utils/api'
import TeacherLayout from '../../components/teacher/TeacherLayout.vue'

const router = useRouter()

// 题目数据
const questionsData = ref<any[]>([])
const searchQuery = ref('')
const courseFilter = ref('')
const typeFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取题目列表
const fetchQuestions = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      content: searchQuery.value,
      courseId: courseFilter.value,
      questionType: typeFilter.value
    }

    const response = await get('/question-bank/query', params)
    console.log('题目数据响应:', response)

    if (response.code === 200) {
      // 直接使用data数组，根据实际返回格式
      questionsData.value = response.data || []
      // 使用dataCount作为总数
      total.value = response.dataCount || 0
    } else {
      ElMessage.error(response.msg || '获取题目列表失败')
      questionsData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取题目列表异常:', error)
    ElMessage.error('网络错误，请稍后重试')
    questionsData.value = []
    total.value = 0
  }
}

// 根据题型ID获取标签类型
const getTypeTagType = (typeId: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary', // 单选题
    2: 'success', // 多选题
    3: 'warning'  // 判断题
  }
  return typeMap[typeId] || 'info'
}

// 根据难度获取标签类型
const getDifficultyTagType = (difficulty: string) => {
  const difficultyMap: Record<string, string> = {
    '简单': 'success',
    '中等': 'warning',
    '困难': 'danger'
  }
  return difficultyMap[difficulty] || 'info'
}

// 页面挂载时获取数据
onMounted(() => {
  fetchQuestions()
})

const handleAdd = () => {
  router.push('/teacher/question/add')
}

const handleEdit = (row: any) => {
  // 编辑功能，带上题目ID跳转到编辑页面
  router.push({ path: '/teacher/question/edit', query: { id: row.questionId } })
}

const handleDelete = async (questionId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该题目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用删除接口（使用GET方法，因为后端使用@RequestParam接收参数）
    const response = await get('/question-bank/delete', { questionId })
    
    if (response.code === 200) {
      ElMessage.success(response.msg || '删除成功')
      // 删除成功后刷新列表
      fetchQuestions()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    // 用户取消删除或发生错误
    if (error !== 'cancel') {
      console.error('删除题目异常:', error)
    }
  }
}

const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置到第一页
  fetchQuestions()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchQuestions()
}

const handleCurrentChange = (current: number) => {
  currentPage.value = current
  fetchQuestions()
}
</script>

<style>
/* 全局样式，设置body背景为白色 */
body {
  background-color: #ffffff;
  margin: 0;
  padding: 0;
}
</style>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  text-align: center;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.question-detail {
  padding: 10px;
  background: #fafafa;
  border-radius: 6px;
}

.question-content {
  margin-bottom: 10px;
  line-height: 1.6;
  word-break: break-word;
}

.options {
  margin-bottom: 10px;
}

.option-item {
  padding: 8px 12px;
  margin-bottom: 6px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
}

.option-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.15);
}

.correct-option {
  border-color: #67c23a;
  background: #f0f9ff;
}

.correct-option::after {
  content: '✓';
  color: #67c23a;
  margin-left: auto;
  font-weight: bold;
}

.option-label {
  margin-right: 8px;
  font-weight: bold;
  color: #409eff;
  min-width: 20px;
}

.answer-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
}

.score-value {
  font-weight: bold;
  color: #e6a23c;
  font-size: 16px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 15px 0;
  background: #fff;
  border-top: 1px solid #ebeef5;
}

.question-list-card {
  background-color: #fff;
  margin: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}


/* 响应式设计 */
@media (max-width: 1200px) {
  .search-bar {
    flex-wrap: wrap;
    gap: 10px;
  }

  .question-detail {
    font-size: 14px;
  }
}

/* 滚动条美化 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f0f0f0;
  border-radius: 4px;
}

/* 移动端响应式设计 */
@media (max-width: 768px) {
  .question-list-card {
    margin: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .search-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .search-bar .el-input,
  .search-bar .el-select {
    width: 100% !important;
    margin-left: 0 !important;
  }
  
  .pagination {
    justify-content: center;
  }
}
</style>